// pages/collection/sheet/sheet.js
const db = wx.cloud.database()

Page({
  data: {
    pageIndex: 0,
    sheetKey: '',
    sheetIndex: 0,
    hasSelect: false,
    showDialog: false,
    sheetFlag: -1,
    keys: [],
    sheet: [],
    selectSheets: [],
    buttons: [{
      text: '取消'
    }, {
      text: '确定'
    }]
  },
  onLoad: function (options) {
    if (!options.key)
      return
    console.log(options)
    var sheet_key = options.key
    wx.setNavigationBarTitle({
      title: sheet_key + "表"
    })
    this.setData({
      sheetKey: sheet_key
    })
    this._clearSheetData()
    this._get_sheet_data()
  },
  onShow: function (e) {
    this._updateSheetData()
  },
  //更新Item单条数据
  _updateSheetData() {
    console.log("_updateSheetData")
    var _this = this
    var sheetList = this.data.sheet
    var sheetKey = this.data.sheetKey
    var sheetData = this.data.sheetData
    if (sheetData == null)
      return
    db.collection(sheetKey).doc(sheetData._id).get({
      success: function (res) {
        var newSheet = res.data
        console.log(newSheet)
        //添加index属性，更新sheet列表数据
        newSheet.index = sheetData.index
        //数组先添加再删除元素
        sheetList.splice(sheetData.index - 1, 0, newSheet)
        sheetList.splice(sheetData.index, 1)
        _this.setData({
          sheet: sheetList
        })
      },
      fail: console.error
    })
  },
  //清除数据
  _clearSheetData() {
    this.setData({
      sheet: [],
      pageIndex: 0,
      hasSelect: false
    })
  },
  //获取数据表的数据
  _get_sheet_data() {
    console.log("_get_sheet_data")
    //条件逻辑
    const _ = db.command
    var sheetFlag = this.data.sheetFlag
    var whereCon = {}
    if (sheetFlag != -1)
      whereCon.flag = _.exists(sheetFlag == 1)
    //本地参数
    var _this = this
    var sheetKey = this.data.sheetKey
    var pageIndex = this.data.pageIndex
    var oldSheet = this.data.sheet
    db.collection(sheetKey).where(whereCon)
      .skip(10 * pageIndex) // 跳过结果集中的前 10 条，从第 11 条开始返回
      .limit(10) // 限制返回数量为 10 条
      .get({
        success: res => {
          // console.log(res.data)
          if (res.data.length <= 0) {
            wx.showToast({
              title: '已经加载所有数据'
            })
            return
          }
          var keys1 = _this._get_sheet_keys(res.data)
          let newSheet = oldSheet.concat(res.data)
          for (var i = 0; i < newSheet.length; i++) {
            newSheet[i].index = i + 1
          }
          // console.log(newSheet)
          // console.log(keys1)
          this.setData({
            keys: keys1,
            sheet: newSheet,
            pageIndex: pageIndex + 1
          })
        },
        fail: err => {
          console.error(err)
        }
      })
  },
  //获取对象里面的属性值，返回index和4个属性的集合
  _get_sheet_keys(sheetList) {
    var keys1 = ['index'];
    var dataLen = sheetList.length
    //如果没有数据返回空数据的标题
    if (dataLen == 0) {
      for (i = 0; i < 4; i++) {
        keys1.push(null)
      }
      return keys1;
    }
    //判断数量大于1取第二条；否则取第一条数据里面的属性值
    var sheetObj = sheetList[dataLen > 1 ? 1 : 0]
    var sheetObjAtts = Object.keys(sheetObj).length
    var index = 0;
    // console.log("keys1", keys1)
    for (var p1 in sheetObj) {
      //如果属性数量小于{5}或者属性不等于'_id'
      var _idIn = sheetObjAtts < 5 || p1 != "_id"
      //如果属性数量小于{6}或者属性不等于'_openid'
      var _openidIn = sheetObjAtts < 6 || p1 != "_openid"
      if (sheetObj.hasOwnProperty(p1) && _idIn && _openidIn && index < 4) {
        keys1.push(p1);
        index++
      }
    }
    return keys1;
  },
  //数据表Item点击事件
  onSheetItemClick(e) {
    console.log(e)
    var sheetData = e.currentTarget.dataset.sheetdata
    this.startToSheetDetail(sheetData, "")
  },
  //跳转到数据表详情界面
  startToSheetDetail(sheetData, flag) {
    console.log(sheetData)
    var sheetKey = this.data.sheetKey
    var sheetStr = JSON.stringify(sheetData);
    wx.navigateTo({
      url: '../sheetdt/sheetdt?sheetKey=' + sheetKey + "&flag=" + flag + "&sheetStr=" + encodeURIComponent(sheetStr)
    })
    this.setData({
      sheetData: sheetData
    })
  },
  //数据表Item选中事件
  onSheetItemSleect(e) {
    console.log("sheetItemLongPress", e)
    var sheetData = e.currentTarget.dataset.sheetdata
    var oldSheet = this.data.sheet
    var selectItems = []
    var hasSelect = false //是否包含选中项
    for (var i = 0; i < oldSheet.length; i++) {
      if (oldSheet[i]._id == sheetData._id) {
        var press = oldSheet[i].longPressed
        oldSheet[i].longPressed = !press;
      }
      if (oldSheet[i].longPressed == true) {
        var selSheet = {
          _id: oldSheet[i]._id,
          index: oldSheet[i].index
        }
        hasSelect = true
        selectItems.push(selSheet)
      }
    }
    this.setData({
      sheet: oldSheet,
      hasSelect: hasSelect,
      selectSheets: selectItems
    })
  },
  //删除按钮点击监听
  deleteClick() {
    this.setData({
      showDialog: true
    })
  },
  //弹窗按钮监听
  tapDialogButton(e) {
    console.log(e)
    var _this = this
    var btnIndex = e.detail.index
    var selectSheets = this.data.selectSheets
    var oldSheets = this.data.sheet
    this.setData({
      showDialog: false
    })
    if (btnIndex == 1) {
      for (var i = oldSheets.length - 1; i >= 0; i--) {
        for (var j = selectSheets.length - 1; j >= 0; j--) {
          if (oldSheets[i]._id == selectSheets[j]._id) {
            oldSheets.splice(i, 1)
            _this.deleteSheetInDb(selectSheets[j]._id)
          }
        }
      }
      _this.setData({
        sheet: oldSheets
      })
    }
  },
  //删除数据库数据
  deleteSheetInDb(sheetId) {
    var _this = this
    var sheet_key = this.data.sheetKey
    db.collection(sheet_key).doc(sheetId).remove({
      success: function (res) {
        console.log(res.data)
        _this.setData({
          hasSelect: false
        })
        wx.showToast({
          icon: "none",
          title: '删除成功!'
        })
      }
    })
  },
  //添加数据表
  onAddSheetClick(e) {
    var sheetData = e.currentTarget.dataset.sheetdata
    this.startToSheetDetail(sheetData, "add")
  },
  //加载更多数据
  lookMorePage(e) {
    this._get_sheet_data()
  },
  //筛选Flag数据
  selectFlagData(e) {
    var sheetFlag = this.data.sheetFlag
    switch (sheetFlag) {
      case 0:
      case -1:
        sheetFlag = 1;
        break;
      case 1:
        sheetFlag = 0;
        break
    }
    this.setData({
      sheetFlag: sheetFlag
    })
    this._clearSheetData()
    this._get_sheet_data()
  }
})